/****************************************************************************
** Uses econographicsForPCA.dta to produce correlations						*
** matrices and PCA analysis. Adds components to 							*
** econographicsTransformedWithComponents.dta								*
**																			*
** Creates a weighted correlation matrix in memory by calling 				*
** 	createCorrelationMatrix.do												*
** 																			*		
** Produced by Erik Snowberg, October 13, 2022								*
** 		Based on Code by Jonathan Chapman and Erik Snowberg					*
****************************************************************************/

/****************************************************************************
** To produce latex correlation tables that look nice based on output of	*
** this code, take the following steps:										*
** 	1) replace (0. with (.													*
**	2) replace - with $-$													*
**	3) (only for risk) remove correlation between EE and constituent 		*
** 		measures, and CR and constituent measures.							*
**	4) move \hlt commands, which define the colors in the latex table,		*
** 		at the end of rows to before the number (rather than after, which 	*
**		works in all other positions in the table. If the number is 		*
**		negative, then you also need to surround the number with { }		*
**	5) add copy of rows, but with just the colors, and \, after each color,	*
**		after the standard error row. then [-.175in] of deleted space		*
**	6) subtract [-.01in] after each midline to get rid of white lines		*
**	7) add [.025in] after each cell to get right spacing					*
****************************************************************************/



/**********************************************************************
** Create the correlation matrix
**********************************************************************/
/**********************************
**Define macros needed to run code
***********************************/
// List of variables with two measures. Note that it is assumed that these measures
// are labeled "1" and "2". Hence the renaming of some variables
global  twoByTwoList =`"WTP WTA riskAversionCRSure riskAversionCRLottery commonRatio endowmentEffect "' ///		
					+ `"advanInequalityAversion disadInequalityAversion patience riskAversionUrn riskAversionGain "' ///
					+ `"riskAversionMixGainLoss riskAversionLoss "' ///		
					+ `"ambiguityAversion compoundAversion qualOverPrecise "' ///
					+ `"overPlacementFacts overEstimateIQ reciprocityHigh reciprocityLow "'
// List of variables with measures where non-orthogonal error is an issue 
// since the measures are constructed with common compoenents
** These need to entered in PAIRS relating to the correlation that should be implemented
** with the separate procedure
** e.g. if want the correlation with endowment effect and WTP and also WTA, endowment effect enters twice
** NOTE: all these variables should also be included in the twoByTwoList above
global  twoByTwoListNonOrthog =`"ambiguityAversion compoundAversion "' ///
							+ `"endowmentEffect WTA "' ///
							+ `"endowmentEffect WTP "' ///
							+ `"commonRatio riskAversionCRSure "' ///
							+ `"commonRatio riskAversionCRLottery "' ///
							+ `"ambiguityAversion riskAversionUrn "' ///
							+ `"compoundAversion riskAversionUrn "' ///
							+ `"qualOverPrecise overPlacementFacts "' 

// List of variables with one measure		
global  oneByTwoListEV =`"altruism trust punishSender punishReceiver PSext PRext"'
	
/*****************
**Run the Code
******************/
// This defines a program to run the non-orthogonal ORIV procedure, 
// and then constructs separate matrices with the correlations and SEs
// note that these matricies are all stored in Stata memory
use "${datapath}econographicsForPCA.dta", clear
do "${dofilepath}createCorrelationMatrixForPCA.do"

///***********************************************************************
// 4.2 Links Between Social Preferences
// Estimate PCAs using list of social preferences 
// Then use the results  to calculate factor weights and construct the risk factors 
///***********************************************************************
// Variables to be included in PCA
local varlistSocial "reciprocityLow reciprocityHigh altruism trust punishSender punishReceiver advanInequalityAversion disadInequalityAversion"

// Need to create a subset of the correlation matrix with these variables
** First the columns
cap matrix drop B
local r=rowsof(corr2)
foreach i in `varlistSocial'  {
  matrix B= nullmat(B), corr2[1..`r',colnumb(corr2,"`i'")]
}
** Now the rows
cap matrix drop C
local c=colsof(B)
foreach i in  `varlistSocial'  {
  matrix C= nullmat(C) \ B[rownumb(B,"`i'"),1..`c']  
}

cap mat drop MSocial
mat rename C MSocial

// PCA (make sure number of obs is correct)
pcamat MSocial, n(1000) forcepsd 

// Screeplot - number of factors
fapara, reps(100) pca setseed(546557)
gr export "${outputpath}ScreeSocial.eps", fontface(Times) replace
window manage close graph

pcamat MSocial, n(1000) forcepsd components(3)
rotate

****************************************************************************************************************
*** Output correlation matrix and component matrix into latex
****************************************************************************************************************
// Start by creating a subset of the SE matrix to match the correlation matrix
** First the columns
cap matrix drop Bse
local r=rowsof(se)
display "`r'"
foreach i in `varlistSocial' {
  matrix Bse= nullmat(Bse), se[1..`r',colnumb(se,"`i'")]
}
** Now the rows
cap matrix drop Cse
local c=colsof(Bse)
foreach i in  `varlistSocial'  {
  matrix Cse= nullmat(Cse) \ Bse[rownumb(Bse,"`i'"),1..`c']  
}
cap mat drop MSocialSE 
mat rename Cse MSocialSE

// Now reorganize the varibles
cap mat drop O
local r=rowsof(MSocial)
foreach i in  `varlistSocial' {
	matrix O=nullmat(O),MSocial[1..`r',colnumb(MSocial,"`i'")]
	matrix O=nullmat(O),MSocialSE[1..`r',colnumb(MSocialSE,"`i'")]
}

// Build highlighting matrix
cap drop mat tmp
local c = colsof(MSocial)
local r = rowsof(MSocial)
matrix tmp = J(`r',`c',0)
forvalues i = 1/`r' {
	forvalues j = 1/`c' {
		matrix tmp[`i',`j'] = floor((abs(MSocial[`i',`j'])-0.01)/0.05)
	}
}

// Now duplicate
matrix replicate = J(1,2,1)
matrix highlight = tmp#replicate



// 1) Social Correlations
//remember to move \hlt into the cell if it is the last column in a row...
#delimit;
frmttable using ${outputpath}socialCorrelations.tex, 
		tex statmat(O) sdec(2\3) replace fragment plain nocenter annotate(highlight) 
		asymbol("\hltA" "\hltB" "\hltC" "\hltD" "\hltE" "\hltF" "\hltG" "\hltH" "\hltI" "\hltJ" "\hltK" "\hltL" "\hltM" "\hltN" "\hltO" "\hltP" "\hltQ" "\hltR" "\hltS")
		ctitles("Reciprocity: Low","Reciprocity: High","Altruism","Trust",
				"Anti-Social Punishment","Pro-Social Punishment",
				"Dislike Having More", "Dislike Having Less")
		rtitles("Reciprocity:" \ "~~Low" \ 
				"Reciprocity:" \ "~~High" \ 
				"Altruism" \ "~~(dictator)" \ 
				"Trust" \ "" \
				"Anti-Social" \ "~~Punishment" \ 
				"Pro-Social" \ "~~Punishment" \
				"Dislike" \ "~~Having More" \ 
				"Dislike" \ "~~Having Less")
		substat(1);
#delimit cr	

// 2) PCA
cap mat drop out
matrix out = e(r_L) , e(Psi)'
#delimit;
frmttable using ${outputpath}socialComponents.tex , 
		tex statmat(out) sdec(2) replace fragment plain nocenter
		ctitles("", "Generosity" , "Punishment" , "Inequality Aversion", "Unexplained")
		rtitles("Reciprocity: Low" \ 
				"Reciprocity: High" \
				"Altruism" \ 
				"Trust" \
				"Anti-Social Punishment" \ 
				"Pro-Social Punishment" \
				"Dislike Having More" \ 
				"Dislike Having Less");
#delimit cr	


///***********************************************************************
// 4.3 Links Between Risk Attitudes
///***********************************************************************

///***********************************************************************
// Correlation Matrix 
///***********************************************************************
// Start by creating a subset of the SE matrix to match the correlation matrix
// Include common ratio and endowment effect
#delimit;
local varlistRisk "WTA riskAversionGain riskAversionLoss riskAversionMixGainLoss 
					WTP riskAversionCRSure riskAversionCRLottery 
					ambiguityAversion compoundAversion
					endowmentEffect commonRatio";
#delimit cr


// Need to create a subset of the correlation matrix with these variables
** First the columns
cap matrix drop B
local r=rowsof(corr2)
foreach i in `varlistRisk'  {
  matrix B= nullmat(B), corr2[1..`r',colnumb(corr2,"`i'")]
}
** Now the rows
cap matrix drop C
local c=colsof(B)
foreach i in  `varlistRisk'  {
  matrix C= nullmat(C) \ B[rownumb(B,"`i'"),1..`c']  
}

cap mat drop MRisk
mat rename C MRisk

//now for s.e.
** First the columns
cap matrix drop Bse
local r=rowsof(se)
display "`r'"
foreach i in `varlistRisk' {
  matrix Bse= nullmat(Bse), se[1..`r',colnumb(se,"`i'")]
}
** Now the rows
cap matrix drop Cse
local c=colsof(Bse)
foreach i in  `varlistRisk'  {
  matrix Cse= nullmat(Cse) \ Bse[rownumb(Bse,"`i'"),1..`c']  
}
cap mat drop MRiskSE 
mat rename Cse MRiskSE

// Now reorganize the varib
cap mat drop O
local r=rowsof(MRisk)
foreach i in  `varlistRisk' {
	matrix O=nullmat(O),MRisk[1..`r',colnumb(MRisk,"`i'")]
	matrix O=nullmat(O),MRiskSE[1..`r',colnumb(MRisk,"`i'")]
}

// Build highlighting matrix
cap drop mat tmp
local c = colsof(MRisk)
local r = rowsof(MRisk)
matrix tmp = J(`r',`c',0)
forvalues i = 1/`r' {
	forvalues j = 1/`c' {
		matrix tmp[`i',`j'] = floor(abs(abs(MRisk[`i',`j'])-0.01)/0.05)
	}
}

// Now duplicate
matrix replicate = J(1,2,1)
matrix highlight = tmp#replicate


// 2) Risk Correlations
//remember to move \hlt into the cell if it is the last column in a row...
#delimit;
frmttable using ${outputpath}riskCorrelations.tex , 
		tex statmat(O) sdec(2\3) replace fragment plain nocenter annotate(highlight)
		asymbol("\hltA" "\hltB" "\hltC" "\hltD" "\hltE" "\hltF" "\hltG" "\hltH" "\hltI" "\hltJ" "\hltK" "\hltL" "\hltM" "\hltN" "\hltO" "\hltP" "\hltQ" "\hltR" "\hltS")
		ctitles("", "WTA", "Risk Aversion: Gains", "Risk Aversion: Losses", "Risk Aversion: Gain / Loss", 
				"WTA", "Risk A.: CR Certain", "Risk A.: CR Lottery", 
				"Ambiguity Aversion", "Compound Lottery Aversion",
				"Endowment Effect", "Common Ratio")
		rtitles("WTA" \ "" \ 
				"Risk Aversion:" \ "~~Gains" \ 
				"Risk Aversion" \ "~~Losses" \ 
				"Risk Aversion:" \ "~~Gain / Loss" \
				"WTP" \ "" \ 
				"Risk Aversion:" \ "~~CR Certain" \ 
				"Risk Aversion:" \ "~~CR Lottery" \ 
				"Ambiguity" \ "~~Aversion" \ 
				"Compound" \ "~~Aversion" \ 
				"Endowment" \ "~~Effect" \ 
				"Common" \ "~~Ratio")
	  substat(1);
#delimit cr	

///***********************************************************************
// PCA
///***********************************************************************
// Variable list: risk (do not include commonRatio and endowment effect for
// initial pca
#delimit;
local varlistRisk "WTA riskAversionGain riskAversionLoss riskAversionMixGainLoss 
					WTP riskAversionCRSure riskAversionCRLottery 
					ambiguityAversion compoundAversion";
#delimit cr


// Need to create a subset of the correlation matrix with these variables
** First the columns
cap matrix drop B
local r=rowsof(corr2)
foreach i in `varlistRisk'  {
  matrix B= nullmat(B), corr2[1..`r',colnumb(corr2,"`i'")]
}
** Now the rows
cap matrix drop C
local c=colsof(B)
foreach i in  `varlistRisk'  {
  matrix C= nullmat(C) \ B[rownumb(B,"`i'"),1..`c']  
}

cap mat drop MRisk
mat rename C MRisk

// PCA (make sure number of obs is correct)
pcamat MRisk, n(1000) forcepsd 

//screeplot
fapara, reps(100) pca setseed(546557)
gr export ${outputpath}ScreeRisk.eps, fontface(Times) replace
window manage close graph

pcamat MRisk, n(1000) forcepsd components(3)
rotate

// LaTeX output of PCA components
cap mat drop out
matrix out = e(r_L) , e(Psi)'
#delimit;
frmttable using ${outputpath}riskComponents.tex , 
		tex statmat(out) sdec(2) replace fragment plain nocenter
		ctitles("", "RA: WTA" , "RA: WTP" , "Uncertainty", "Unexplained")
		rtitles("WTA" \ 
				"Risk Aversion: Gains" \ 
				"Risk Aversion: Losses" \ 
				"Risk Aversion: Gain / Loss" \
				"WTP" \ 
				"Risk Aversion: CR Certain" \ 
				"Risk Aversion: CR Lottery" \ 
				"Ambiguity Aversion" \ 
				"Compound Lottery Aversion");
#delimit cr	


///***********************************************************************
// 4.4 Links Between All Measures
// Estimate three sets of PCAs: i) raw measures ii) derived measures iii) both raw and
// derived
// Then use the latter to calculate factor weights and construct the risk factors 
///***********************************************************************
//variables are ordered social + risk + other
#delimit;
local varlistAll "reciprocityLow reciprocityHigh altruism trust punishSender 
					punishReceiver advanInequalityAversion disadInequalityAversion 
					WTA riskAversionGain riskAversionLoss riskAversionMixGainLoss 
					WTP riskAversionCRSure riskAversionCRLottery 
					ambiguityAversion compoundAversion
					overEstimateIQ overPlacementFacts qualOverPrecise patience";
#delimit cr
// Need to create a subset of the correlation matrix with these variables
** First the columns
cap matrix drop B
local r=rowsof(corr2)
foreach i in `varlistAll'  {
  matrix B= nullmat(B), corr2[1..`r',colnumb(corr2,"`i'")]
}
** Now the rows
cap matrix drop C
local c=colsof(B)
foreach i in  `varlistAll'  {
  matrix C= nullmat(C) \ B[rownumb(B,"`i'"),1..`c']  
}

cap mat drop MAll
mat rename C MAll

// PCA (make sure number of obs is correct)
pcamat MAll, n(1000) forcepsd 

// screeplot
fapara, reps(100) pca setseed(546557)
gr export ${outputpath}ScreeAll.eps, fontface(Times) replace
window manage close graph

pcamat MAll, n(1000) forcepsd components(6)
rotate


// Output compenents to Latex Table
cap mat drop out
matrix out = e(r_L) , e(Psi)'
#delimit;
frmttable using ${outputpath}allComponents.tex , 
		tex statmat(out) sdec(2) replace fragment plain nocenter
		ctitles("", "Generosity" , "RA: WTA" , "WTP / Inequality", "Overconfidence" , "Patience" , "Uncertainty", "Unexplained")
		rtitles("Reciprocity: Low" \ 
				"Reciprocity: High" \
				"Altruism" \ 
				"Trust" \
				"Anti-Social Punishment" \ 
				"Pro-Social Punishment" \
				"Dislike Having More" \ 
				"Dislike Having Less" \
				"WTA" \ 
				"Risk Aversion: Gains" \ 
				"Risk Aversion: Losses" \ 
				"Risk Aversion: Gain / Loss" \
				"WTP" \ 
				"Risk Aversion: CR Certain" \ 
				"Risk Aversion: CR Lottery" \ 
				"Ambiguity Aversion" \ 
				"Compound Lottery Aversion"\
				"Overestimation" \ 
				"Overplacement" \ 
				"Overprecision" \ 
				"Patience");
#delimit cr	

****************************************************************************************************************
*** Generate the combined economic components using the overall list
****************************************************************************************************************
drop _all
mat define W=e(r_L)'
svmat W
gen component=_n

local counter=0

foreach i in `varlistAll' {
	local counter=`counter'+1
	rename  W`counter' `i'_c_
}

// Then we reshape to get it in the right form
gen row=1
reshape wide `varlistAll'_c_, i(row) j(component) 
drop row

// Now save the file with the factor weights
tempfile weights
save `weights', replace

****************************************************************************************************************
*** Add the factor weights to the survey dataset
**************************************************************************************************************** 
// Use the version of the robust econographics dataset with standardized measures defined at the top of this .do file,
// and the risk component /social components from above
use "${datapath}econographicsTransformedWithComponents.dta", clear
//append the factors weights file defined in the previous PCA
append using `weights'

// Now ``spread'' the component and multiply it by either the average measure for the variable
// or by the two components. First those that have only one observation
// This list of variables will match those from the correlation matrix used to generate the factors.
// Number of factors in loop should match the number generated from the PCA
local varlistOneMeasure "altruism trust punishSender punishReceiver patience"

foreach varname in `varlistOneMeasure' { 
	forvalues i = 1/6 {
		egen rC_`i'`varname' = max(`varname'_c_`i')
		gen s`i'_`varname' = rC_`i'`varname'*FA`varname'
	}
}

//now those with two measures
#delimit;
local varlistTwoMeasures "reciprocityLow reciprocityHigh 
					advanInequalityAversion disadInequalityAversion 
					WTA riskAversionGain riskAversionLoss riskAversionMixGainLoss 
					WTP riskAversionCRSure riskAversionCRLottery 
					ambiguityAversion compoundAversion
					overEstimateIQ overPlacementFacts qualOverPrecise";
#delimit cr

foreach varname in `varlistTwoMeasures' { 
	forvalues i = 1/6 {
		egen rC_`i'`varname' = max(`varname'_c_`i')
		gen w`i'_`varname' = rC_`i'`varname'*FA`varname'
		gen v`i'1_`varname' = rC_`i'`varname'*FA`varname'1
		gen v`i'2_`varname' = rC_`i'`varname'*FA`varname'2
	}
}

//drop *EconComponent*
egen ORIVEconComponent11 = rowtotal(s1_* v11_*)
egen ORIVEconComponent21 = rowtotal(s2_* v21_*)
egen ORIVEconComponent31 = rowtotal(s3_* v31_*)
egen ORIVEconComponent41 = rowtotal(s4_* v41_*)
egen ORIVEconComponent51 = rowtotal(s5_* v51_*)
egen ORIVEconComponent61 = rowtotal(s6_* v61_*)

egen ORIVEconComponent12 = rowtotal(s1_* v12_*)
egen ORIVEconComponent22 = rowtotal(s2_* v22_*)
egen ORIVEconComponent32 = rowtotal(s3_* v32_*)
egen ORIVEconComponent42 = rowtotal(s4_* v42_*)
egen ORIVEconComponent52 = rowtotal(s5_* v52_*)
egen ORIVEconComponent62 = rowtotal(s6_* v62_*)

egen avgEconComponent1 = rowtotal(s1_* w1_*)
egen avgEconComponent2 = rowtotal(s2_* w2_*)
egen avgEconComponent3 = rowtotal(s3_* w3_*)
egen avgEconComponent4 = rowtotal(s4_* w4_*)
egen avgEconComponent5 = rowtotal(s5_* w5_*)
egen avgEconComponent6 = rowtotal(s6_* w6_*)

drop w1_* w2_* w3_* w4_* w5_* w6_* s1_* s2_* s3_* s4_* s5_* s6_* *_c_*  rC_* ///
		v11_* v21_* v31_* v41_* v51_* v61_* v12_* v22_* v32_* v42_* v52_* v62_*

// Make sure to drop the additional row with the factor weights and any additional variables
drop if _n==1001

//file to be used for later analyses...
save "${datapath}econographicsTransformedWithComponents.dta", replace


///***********************************************************************
// For Appendix
///***********************************************************************

///***********************************************************************
// PCA including common ratio
///***********************************************************************
// Variable list: risk (do not include commonRatio and endowment effect for
// pca
#delimit;
local varlistRisk "WTA riskAversionGain riskAversionLoss riskAversionMixGainLoss 
					WTP commonRatio 
					ambiguityAversion compoundAversion";
#delimit cr


// Need to create a subset of the correlation matrix with these variables
** First the columns
cap matrix drop B
local r=rowsof(corr2)
foreach i in `varlistRisk'  {
  matrix B= nullmat(B), corr2[1..`r',colnumb(corr2,"`i'")]
}
** Now the rows
cap matrix drop C
local c=colsof(B)
foreach i in  `varlistRisk'  {
  matrix C= nullmat(C) \ B[rownumb(B,"`i'"),1..`c']  
}

cap mat drop MRisk
mat rename C MRisk

pcamat MRisk, n(1000) forcepsd components(3)
rotate

// LaTeX output.
cap mat drop out
matrix out = e(r_L) , e(Psi)'
#delimit;
frmttable using ${outputpath}APPRiskComponentsCR.tex , 
		tex statmat(out) sdec(2) replace fragment plain nocenter
		ctitles("", "Risk Aversion: WTA" , "Risk Aversion: WTP" , "Uncertainty", "Unexplained")
		rtitles("WTA" \ 
				"Risk Aversion: Gains" \ 
				"Risk Aversion: Losses" \ 
				"Risk Aversion: Gain / Loss" \
				"WTP" \ 
				"Common Ratio" \ 
				"Ambiguity Aversion" \ 
				"Compound Lottery Aversion");
#delimit cr	

///***********************************************************************
// PCA including the urn measure 
///***********************************************************************
//variables are ordered social + risk + other
#delimit;
local varlistAll "reciprocityLow reciprocityHigh altruism trust punishSender 
					punishReceiver advanInequalityAversion disadInequalityAversion 
					WTA riskAversionGain riskAversionLoss riskAversionMixGainLoss riskAversionUrn 
					WTP riskAversionCRSure riskAversionCRLottery 
					ambiguityAversion compoundAversion
					overEstimateIQ overPlacementFacts qualOverPrecise patience";
#delimit cr
// Need to create a subset of the correlation matrix with these variables
** First the columns
cap matrix drop B
local r=rowsof(corr2)
foreach i in `varlistAll'  {
  matrix B= nullmat(B), corr2[1..`r',colnumb(corr2,"`i'")]
}
** Now the rows
cap matrix drop C
local c=colsof(B)
foreach i in  `varlistAll'  {
  matrix C= nullmat(C) \ B[rownumb(B,"`i'"),1..`c']  
}

cap mat drop MAll
mat rename C MAll

pcamat MAll, n(1000) forcepsd components(6)
rotate

// Output compenents to Latex Table
cap mat drop out
matrix out = e(r_L) , e(Psi)'
#delimit;
frmttable using ${outputpath}APPAllComponentsPlusUrn.tex , 
		tex statmat(out) sdec(2) replace fragment plain nocenter
		ctitles("", "Risk Aversion: WTA",  "Generosity" , "WTP / Inequality", "Overconfidence" , "Patience" , "Uncertainty", "Unexplained")
		rtitles("Negative Reciprocity" \ 
				"Positive Reciprocity" \
				"Altruism" \ 
				"Trust" \
				"Anti-Social Punishment" \ 
				"Pro-Social Punishment" \
				"Dislike Having More" \ 
				"Dislike Having Less" \
				"WTA" \ 
				"Risk Aversion: Gains" \ 
				"Risk Aversion: Losses" \ 
				"Risk Aversion: Gain / Loss" \ 
				"Risk Aversion: Urn" \
				"WTP" \ 
				"Risk Aversion: CR Certain" \ 
				"Risk Aversion: CR Sure" \ 
				"Ambiguity Aversion" \ 
				"Compound Lottery Aversion" \
				"Overestimation" \ 
				"Overplacement" \ 
				"Overprecision" \ 
				"Patience");
#delimit cr	

///***********************************************************************
// PCA without "Dislike Having More"
///***********************************************************************
//variables are ordered social + risk + other
#delimit;
local varlistAll "reciprocityLow reciprocityHigh altruism trust punishSender 
					punishReceiver disadInequalityAversion 
					WTA riskAversionGain riskAversionLoss riskAversionMixGainLoss 
					WTP riskAversionCRSure riskAversionCRLottery 
					ambiguityAversion compoundAversion
					overEstimateIQ overPlacementFacts qualOverPrecise patience";
#delimit cr
// Need to create a subset of the correlation matrix with these variables
** First the columns
cap matrix drop B
local r=rowsof(corr2)
foreach i in `varlistAll'  {
  matrix B= nullmat(B), corr2[1..`r',colnumb(corr2,"`i'")]
}
** Now the rows
cap matrix drop C
local c=colsof(B)
foreach i in  `varlistAll'  {
  matrix C= nullmat(C) \ B[rownumb(B,"`i'"),1..`c']  
}

cap mat drop MAll
mat rename C MAll

pcamat MAll, n(1000) forcepsd components(6)
rotate


// Output compenents to Latex Table
cap mat drop out
matrix out = e(r_L) , e(Psi)'
#delimit;
frmttable using ${outputpath}APPAllComponentsMinusDLM.tex , 
		tex statmat(out) sdec(2) replace fragment plain nocenter
		ctitles("", "Risk Aversion: WTA",  "Generosity" , "WTP / Inequality", "Overconfidence" , "Patience" , "Uncertainty", "Unexplained")
		rtitles("Negative Reciprocity" \ 
				"Positive Reciprocity" \
				"Altruism" \ 
				"Trust" \
				"Anti-Social Punishment" \ 
				"Pro-Social Punishment" \ 
				"Dislike Having Less" \
				"WTA" \ 
				"Risk Aversion: Gains" \ 
				"Risk Aversion: Losses" \ 
				"Risk Aversion: Gain / Loss" \
				"WTP" \ "Risk Aversion: CR Certain" \ 
				"Risk Aversion: CR Lottery" \ 
				"Ambiguity Aversion" \ 
				"Compound Lottery Aversion" \
				"Overestimation" \ 
				"Overplacement" \ 
				"Overprecision" \ 
				"Patience");
#delimit cr	

